﻿using Abp.Domain.Repositories;
using Abp.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using Abp.Linq.Extensions;
using System.Text;
using System.Threading.Tasks;
using Camc.Quality.Bop.TreeObject;
using Camc.Quality.Bop;
using Abp.Domain.Uow;
using Camc.Quality.Quality;
using Camc.Quality.RecordTable.FormBase;
using Camc.Quality.Bop.Dto;
using Camc.Quality.ProductionPlan;
using Camc.Quality.RecordTable.FormClass;

namespace Camc.Quality.ProcessRoute
{
    public class ProcessRouteAppService : QualityAppServiceBase
    {
        private readonly IRepository<BopDesc, Guid> _bopDescRepository;
        private readonly IRepository<ProcessLine, Guid> _processLineRepository;
        private readonly IRepository<BopNode, Guid> _bopNodeRepository;
        private readonly IRepository<TechniqueEntity, Guid> _techniqueEntityRepository;
        private readonly IRepository<ProcessesEntity, Guid> _processesEntityRepository;
        private readonly IRepository<WorkStepEntity, Guid> _workStepEntityRepository;
        private readonly IRepository<TableBase, Guid> _tableBaseEntity;
        private readonly IRepository<ConvertFormBase, Guid> _convertFormBaseEntity;
        private readonly IRepository<ProductionScheduler, Guid> _productionSchedulerRepository;
        private readonly IRepository<LoadPieceEntity, Guid> _loadPieceRepository;
        private readonly IRepository<MakeResourcesEntity, Guid> _makeResourcesEntityRepository;
        private readonly IRepository<VideoEntity, Guid> _videoEntityRepository;


        public ProcessRouteAppService(IRepository<BopDesc, Guid> bopDescRepository,
            IRepository<BopNode, Guid> bopNodeRepository,
            IRepository<ProcessLine, Guid> processLineRepository,
            IRepository<TechniqueEntity, Guid> techniqueEntityRepository,
            IRepository<ProcessesEntity, Guid> processesEntityRepository,
            IRepository<WorkStepEntity, Guid> workStepEntityRepository,
            IRepository<TableBase, Guid> tableBaseEntity,
            IRepository<ConvertFormBase, Guid> convertFormBaseEntity,
            IRepository<ProductionScheduler, Guid> productionSchedulerRepository,
            IRepository<LoadPieceEntity, Guid> loadPieceRepository,
            IRepository<MakeResourcesEntity, Guid> makeResourcesEntityRepository,
            IRepository<VideoEntity, Guid> videoEntityRepository
            )
        {
            _bopDescRepository = bopDescRepository;
            _bopNodeRepository = bopNodeRepository;
           
            _processLineRepository = processLineRepository;
            _techniqueEntityRepository = techniqueEntityRepository;
            _processesEntityRepository = processesEntityRepository;
            _workStepEntityRepository = workStepEntityRepository;
            _tableBaseEntity = tableBaseEntity;
            _convertFormBaseEntity = convertFormBaseEntity;
            _productionSchedulerRepository = productionSchedulerRepository;
            _loadPieceRepository = loadPieceRepository;
            _makeResourcesEntityRepository = makeResourcesEntityRepository;
            _videoEntityRepository = videoEntityRepository;
        }
        #region 路线CRUD
        /// <summary>
        /// 新建路线
        /// </summary>
        /// <param name="input"></param>
        public void CreateNewRoutes(ProcessTaskDto input)
        {
            var processTask = ObjectMapper.Map<BopDesc>(input);
            processTask.ProcessStatus = (ProcessStatus)0;
            processTask.IsUsed = (Bop.IsUsed)1;
            processTask.ReleaseTime = DateTime.Now;
            processTask.ReleaseUserId = GetCurrentUser().Id;
            processTask.ReleaseTime = DateTime.Now;
            _bopDescRepository.Insert(processTask);
        }
        /// <summary>
        /// 修改路线
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool UpadteRoute(ProcessTaskDto input)
        {
            var processTask = _bopDescRepository.FirstOrDefault(d => d.Id == input.Id);
            if (processTask != null)
            {
                processTask.Model = input.Model;
                processTask.LotNo = input.LotNo;
                processTask.ModelId = input.ModelId;
                processTask.LotNoId = input.LotNoId;
                processTask.ModelName = input.ModelName;
                processTask.DrawingNo = input.DrawingNo;
                processTask.StageSign = input.StageSign;
                processTask.WorkingHourStatus = input.WorkingHourStatus;
                _bopDescRepository.Update(processTask);
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 根据Id删除路线或者节点
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool DeleteRouteById(Guid Id)
        {
            var processTask = _bopDescRepository.FirstOrDefault(d => d.Id == Id);
            if (processTask != null)
            {

                var node = _bopNodeRepository.FirstOrDefault(x => x.BopDescId == Id);
                if (node != null)
                {
                    throw new UserFriendlyException("已维护节点信息，不能删除");
                }
                else
                {
                    _bopDescRepository.Delete(processTask);
                }
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 根据型号、发次、图号查询工艺路线
        /// </summary>
        /// <param name="parm"></param>
        /// <param name="bopDescId"></param>
        /// <returns></returns>
        public List<BopDescDto> GetProcessRoute(ProcessTaskDto parm, Guid bopDescId)
        {
            return ObjectMapper.Map<List<BopDescDto>>(_bopDescRepository.GetAll().Where(d => d.Id != bopDescId)
             .WhereIf(parm.ModelId != null, p => p.ModelId == parm.ModelId)
             .WhereIf(parm.LotNoId != null, p => p.LotNoId == parm.LotNoId)
             .WhereIf(string.IsNullOrEmpty(parm.DrawingNo) == false, p => p.DrawingNo.Contains(parm.DrawingNo)));
        }
        //public List<BopDescDto> GetProcessRoute(ProcessTaskDto parm, bool publish)
        //{
        //    return ObjectMapper.Map<List<BopDescDto>>(_bopDescRepository.GetAll()
        //     .WhereIf(parm.ModelId != null, p => p.ModelId == parm.ModelId)
        //     .WhereIf(parm.LotNoId != null, p => p.LotNoId == parm.LotNoId)
        //     .WhereIf(string.IsNullOrEmpty(parm.DrawingNo) == false, p => p.LotNo.Contains(parm.DrawingNo)))
        //     ;
        //}
        #endregion

        /// <summary>
        /// 删除节点校验节点是否可以删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async  Task<bool>  DeleteChechkNode(Guid Id)
        {

            int route = RouteType(Id);
            if (route == 1)
            {
                int childCount = await _bopNodeRepository.CountAsync(d => d.BopDescId == Id);
                if (childCount > 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }

            }
            if (route == 2)
            {
                int childCount =await _bopNodeRepository.CountAsync(d => d.ParentId == Id);
                if (childCount > 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            if (route == 3)
            {
                var tech = await _bopNodeRepository.FirstOrDefaultAsync(d => d.Id == Id);
                var techId = tech.TechniqueEntityId;
                int childCount =await _processesEntityRepository.CountAsync(d => d.TechniqueEntityId == techId);
                if (childCount > 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            if (route == 4)
            {
                int childCount =await _workStepEntityRepository.CountAsync(d => d.ProcessesEntityId == Id);
                if (childCount > 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            return true;
        }

        /// <summary>
        /// 保存节点信息
        /// </summary>
        /// <param name="processDesignDto"></param>
        public async Task<ProcessRouteResult>  SaveProcess(ProcessDesignDto processDesignDto)
        {
            ProcessRouteResult processRouteResult = new ProcessRouteResult();
            try
            {
                //判断是否计算工时
                processRouteResult.flag = false;
                //处理线段关系表先删除同一批次的，然后插入
                var processLineArray = _processLineRepository.GetAll().Where(d => d.PPtr == processDesignDto.ParentId).ToList();
                foreach (var item in processLineArray)
                {
                     _processLineRepository.HardDelete(item);
                }
                foreach (var item in processDesignDto.ProcessLineList)
                {
                    item.PPtr = processDesignDto.ParentId;
                    item.BopDescId = processDesignDto.BopDescId;
                     _processLineRepository.Insert(ObjectMapper.Map<ProcessLine>(item));
                }
                List<Guid> updateArr = new List<Guid>();
                List<Guid> deleteArr = new List<Guid>();
                List<Guid> addArr = new List<Guid>();
                int routeType = RouteType(processDesignDto.ParentId);

                var designPPtr = processDesignDto.ProcessNodeList.FirstOrDefault(d => d.Key == processDesignDto.ParentId);
                if (routeType == 1 || routeType == 2)
                {
                    var pptrNode = _bopNodeRepository.GetAll().Where(c => c.Id == processDesignDto.ParentId).FirstOrDefault();//父节点
                    var nodeGuidArrayData = _bopNodeRepository.GetAll().Where(d => d.ParentId == processDesignDto.ParentId);
                    var nodeGuidArray = nodeGuidArrayData.Select(d => d.Id);
                    //过滤掉父亲节点
                    var proDesignArray = processDesignDto.ProcessNodeList.Where(d => d.Key != processDesignDto.ParentId).Select(d => d.Key);
                    //更新
                    updateArr = nodeGuidArray.Intersect(proDesignArray).ToList();
                    //删除
                    deleteArr = nodeGuidArray.Except(proDesignArray).ToList();
                    //添加
                    addArr = proDesignArray.Except(nodeGuidArray).ToList();
                    foreach (var item in addArr)
                    {
                        var node = ObjectMapper.Map<List<BopNode>>(processDesignDto.ProcessNodeList.Where(d => d.Key == item)).FirstOrDefault();
                        int sort = 0;
                        int nodeLevel = 0;
                        //父节点和子节点Code
                        string parentCode = string.Empty;
                        string nodeCode = string.Empty;
                        UnitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete);
                        if (pptrNode != null)
                        {
                            string processCode = pptrNode.ProcessCode;
                            //防错：已关联工艺文件的节点不能增加子节点
                            if (string.IsNullOrEmpty(processCode))
                            {
                                //逻辑2，父级节点的改为非叶节点
                                pptrNode.IsLeaf = 0;
                                await _bopNodeRepository.UpdateAsync(pptrNode);
                                ////取层级和父节点Code
                                nodeLevel = pptrNode.NodeLevel;
                                if (nodeLevel == 3)
                                {
                                    processRouteResult.code = 1;
                                    processRouteResult.Message = "不能建立节点，节点最多4层级";
                                    return processRouteResult;
                                    //throw new UserFriendlyException("不能建立节点，节点最多4层级");
                                }
                                parentCode = pptrNode.NodeCode;
                                //取值父节点下子节点数量                            
                                var childCount =  Convert.ToInt32(_bopNodeRepository.Count(c => c.BopDescId == processDesignDto.BopDescId && c.ParentCode == parentCode))  ;
                                childCount++;
                                sort = childCount;
                                nodeCode = parentCode + "-" + childCount.ToString().PadLeft(3, '0');
                            }
                            else
                            {
                                processRouteResult.code = 1;
                                processRouteResult.Message = "已关联工艺文件，不能增加子节点";
                                return processRouteResult;
                                //throw new UserFriendlyException("已关联工艺文件，不能增加子节点");
                            }
                        }
                        else
                        {
                            parentCode = "root";
                            int childCount = Convert.ToInt32(_bopNodeRepository.Count(c => c.BopDescId == processDesignDto.BopDescId));
                            childCount++;
                            sort = childCount;
                            nodeCode = childCount.ToString().PadLeft(3, '0');
                            
                        }
                        node.NodeDrawingNo = processDesignDto.ProcessNodeList.Where(d => d.Key == item).First().NodeDrawingNo;
                        node.WorkingHour = processDesignDto.ProcessNodeList.Where(d => d.Key == item).First().WorkingHour;
                        node.BopDescId = processDesignDto.BopDescId;
                        node.NodeType = (NodeType)1;
                        //逻辑1，新增的都是叶节点
                        node.IsLeaf = 1;
                        //逻辑3，增加层级NodeLevel的保存，原理，父级层级加1
                        node.NodeLevel = nodeLevel + 1;
                        node.ParentCode = parentCode;
                        node.NodeCode = nodeCode;
                        node.ParentId = processDesignDto.ParentId;
                        node.Sort = sort;
                        _bopNodeRepository.Insert(node);
                        UnitOfWorkManager.Current.EnableFilter(AbpDataFilters.SoftDelete);
                    }
                    foreach (var item in updateArr)
                    {
                        var proTemp = processDesignDto.ProcessNodeList.Where(d => d.Key == item);
                        var node = ObjectMapper.Map<List<BopNode>>(proTemp).FirstOrDefault();
                        var bop = _bopNodeRepository.GetAll().Where(c => c.Id == node.Id).FirstOrDefault();
                        if (bop != null)
                        {
                            bop.NodeDrawingNo = node.NodeDrawingNo;
                            bop.Loc = node.Loc;
                            bop.NodeName = node.NodeName;
                            bop.Details = node.Details;
                            bop.Figure = node.Figure;
                            bop.Color = node.Color;
                            bop.Size = node.Size;
                            bop.ParentId = processDesignDto.ParentId;
                            bop.Sort = node.Sort;
                            bop.Fill = node.Fill;
                            bop.WorkingHour = node.WorkingHour;
                            _bopNodeRepository.Update(bop);
                        }
                    }
                    foreach (var item in deleteArr)
                    {
                         _bopNodeRepository.Delete(item);
                    }
                    //更新父节点信息
                    if (routeType == 1)
                    {
                        var bopDesc = _bopDescRepository.GetAll().Where(d => d.Id == processDesignDto.ParentId).FirstOrDefault();
                        bopDesc.Loc = designPPtr.Loc;
                        bopDesc.ModelName = designPPtr.Text;
                        bopDesc.Details = designPPtr.Details;
                        bopDesc.Figure = designPPtr.Figure;
                        bopDesc.Color = designPPtr.Color;
                        bopDesc.Size = designPPtr.Size;
                        bopDesc.Fill = designPPtr.Fill;
                        _bopDescRepository.Update(bopDesc);
                    }
                    else
                    {
                        var bopNode =  _bopNodeRepository.GetAll().Where(d => d.Id == processDesignDto.ParentId).FirstOrDefault();
                        bopNode.Loc = designPPtr.Loc;
                        bopNode.NodeName = designPPtr.Text;
                        bopNode.Details = designPPtr.Details;
                        bopNode.Figure = designPPtr.Figure;
                        bopNode.Color = designPPtr.Color;
                        bopNode.Size = designPPtr.Size;
                        bopNode.Fill = designPPtr.Fill;
                        if (processDesignDto.ProcessNodeList.Count == 1)
                        {
                            bopNode.IsLeaf = 1;
                        }
                         _bopNodeRepository.Update(bopNode);
                    }
                }
                if (routeType == 3)
                {
                    var tempNode =  _bopNodeRepository.GetAll().Where(d => d.Id == processDesignDto.ParentId).FirstOrDefault();
                    var techNode =  _techniqueEntityRepository.GetAll().Where(d => d.Id == tempNode.TechniqueEntityId).FirstOrDefault();
                    if (techNode != null)
                    {
                        var nodeGuidArrayData =  _processesEntityRepository.GetAll().Where(d => d.TechniqueEntityId == techNode.Id);
                        var nodeGuidArray = nodeGuidArrayData.Select(d => d.Id);
                        var proDesignArray = processDesignDto.ProcessNodeList.Where(d => d.Key != processDesignDto.ParentId).Select(d => d.Key);
                        updateArr = nodeGuidArray.Intersect(proDesignArray).ToList();
                        //删除
                        deleteArr = nodeGuidArray.Except(proDesignArray).ToList();
                        //添加
                        addArr = proDesignArray.Except(nodeGuidArray).ToList();
                        foreach (var item in addArr)
                        {
                            var temp = processDesignDto.ProcessNodeList.FirstOrDefault(d => d.Key == item);
                            var processNode = ObjectMapper.Map<ProcessesEntity>(temp);
                            processNode.TechniqueEntityId = techNode.Id;
                            processNode.ProcessesWorking = temp.WorkingHour;
                            processNode.ProcessesName = temp.Text;
                            processNode.Fill = temp.Fill;
                            _processesEntityRepository.Insert(processNode);
                        }
                        foreach (var item in updateArr)
                        {
                            var temp = processDesignDto.ProcessNodeList.FirstOrDefault(d => d.Key == item);
                            var processNode = _processesEntityRepository.GetAll().Where(c => c.Id == temp.Key).FirstOrDefault();
                            if (processNode != null)
                            {
                                processNode.Loc = temp.Loc;
                                processNode.ProcessesName = temp.Text;
                                processNode.Details = temp.Details;
                                processNode.Figure = temp.Figure;
                                processNode.Color = temp.Color;
                                processNode.Size = temp.Size;
                                processNode.Fill = temp.Fill;

                                if (temp.WorkingHour != 0)
                                {
                                    processNode.Fill = "lightblue";
                                }
                                else
                                {
                                    processNode.Fill = "lightgray";
                                }
                                processNode.ProcessesWorking = temp.WorkingHour;
                                _processesEntityRepository.Update(processNode);
                            }
                        }
                        foreach (var item in deleteArr)
                        {
                             _processesEntityRepository.Delete(item);
                        }
                        var bopNode =  _bopNodeRepository.GetAll().Where(d => d.Id == processDesignDto.ParentId).FirstOrDefault();
                        bopNode.Loc = designPPtr.Loc;
                        bopNode.NodeName = designPPtr.Text;
                        bopNode.Details = designPPtr.Details;
                        bopNode.Figure = designPPtr.Figure;
                        bopNode.Color = designPPtr.Color;
                        bopNode.Size = designPPtr.Size;
                        bopNode.Fill = designPPtr.Fill;
                        if (processDesignDto.ProcessNodeList.Count == 1)
                        {
                            bopNode.IsLeaf = 1;
                        }
                         _bopNodeRepository.Update(bopNode);

                        if (processDesignDto.WorkingHourStatus == "0" && processDesignDto.ProcessNodeList.Count > 1)//工序
                        {
                            processRouteResult.flag = true;
                            //UpadateWorkHour(proDesignArray.First());
                        }
                    }
                }
                if (routeType == 4)
                {
                    var nodeGuidArrayData =  _workStepEntityRepository.GetAll().Where(d => d.ProcessesEntityId == processDesignDto.ParentId);
                    var nodeGuidArray = nodeGuidArrayData.Select(d => d.Id);
                    var proDesignArray = processDesignDto.ProcessNodeList.Where(d => d.Key != processDesignDto.ParentId).Select(d => d.Key);
                    updateArr = nodeGuidArray.Intersect(proDesignArray).ToList();
                    //删除
                    deleteArr = nodeGuidArray.Except(proDesignArray).ToList();
                    //添加
                    addArr = proDesignArray.Except(nodeGuidArray).ToList();
                    var pptrNode = _processesEntityRepository.FirstOrDefault(c => c.Id == processDesignDto.ParentId);//父节点
                    foreach (var item in addArr)
                    {
                        var temp = processDesignDto.ProcessNodeList.FirstOrDefault(d => d.Key == item);
                        var workNode = ObjectMapper.Map<WorkStepEntity>(temp);
                        //workNode.WorkStepNumber = Convert.ToInt32(temp.Text);
                        workNode.TechniqueEntityId = pptrNode.TechniqueEntityId;
                        workNode.ProcessesEntityId = processDesignDto.ParentId;
                        //workNode.WorkStepName = temp.Text;
                        workNode.WorkStepWorking = temp.WorkingHour;
                        workNode.Fill = temp.Fill;
                        _workStepEntityRepository.Insert(workNode);
                    }
                    foreach (var item in updateArr)
                    {
                        var temp = processDesignDto.ProcessNodeList.FirstOrDefault(d => d.Key == item);
                        var workNode = _workStepEntityRepository.GetAll().Where(c => c.Id == temp.Key).FirstOrDefault();
                        if (workNode != null)
                        {
                            workNode.Loc = temp.Loc;
                            workNode.WorkStepName = temp.Text;
                            workNode.Details = temp.Details;
                            workNode.Figure = temp.Figure;
                            workNode.Color = temp.Color;
                            workNode.Size = temp.Size;
                            workNode.Fill = temp.Fill;
                            if (temp.WorkingHour != 0)
                            {
                                workNode.Fill = "lightblue";
                            }else
                            {
                                workNode.Fill = "lightgray";
                            }
                            workNode.WorkStepWorking = temp.WorkingHour;
                            _workStepEntityRepository.Update(workNode);
                        }
                    }
                    foreach (var item in deleteArr)
                    {
                         _workStepEntityRepository.Delete(item);
                    }
                    var bopProcess =  _processesEntityRepository.GetAll().Where(d => d.Id == processDesignDto.ParentId).FirstOrDefault();
                    bopProcess.Loc = designPPtr.Loc;
                    bopProcess.ProcessesName = designPPtr.Text;
                    bopProcess.Details = designPPtr.Details;
                    bopProcess.Figure = designPPtr.Figure;
                    bopProcess.Color = designPPtr.Color;
                    bopProcess.Size = designPPtr.Size;
                    bopProcess.Fill = designPPtr.Fill;
                    if (designPPtr.WorkingHour != 0)
                    {
                        bopProcess.Fill = "lightblue";
                    } else
                    {
                        bopProcess.Fill = "lightgray";
                    }
                    bopProcess.ProcessesWorking = designPPtr.WorkingHour;
                    _processesEntityRepository.Update(bopProcess);
                    if (processDesignDto.WorkingHourStatus == "0")//工序
                    {
                        processRouteResult.flag = true;
                        //UpadateWorkHour(bopProcess.Id);
                    }
                    if (processDesignDto.WorkingHourStatus == "1" && processDesignDto.ProcessNodeList.Count > 1)//工步
                    {
                        processRouteResult.flag = true;
                        //UpadateWorkHour(proDesignArray.First());
                    }
                }
                if (routeType == 5)
                {
                    var workNode =  _workStepEntityRepository.GetAll().Where(d => d.Id == processDesignDto.ParentId).FirstOrDefault();
                    workNode.Loc = designPPtr.Loc;
                    workNode.WorkStepName = designPPtr.Text;
                    workNode.Details = designPPtr.Details;
                    workNode.Figure = designPPtr.Figure;
                    workNode.Color = designPPtr.Color;
                    workNode.Size = designPPtr.Size;
                    workNode.Fill = designPPtr.Fill;
                    if (designPPtr.WorkingHour != 0)
                    {
                        workNode.Fill = "lightblue";
                    }else
                    {
                        workNode.Fill = "lightgray";
                    }
                    workNode.WorkStepWorking = designPPtr.WorkingHour;
                    _workStepEntityRepository.Update(workNode);
                    if (processDesignDto.WorkingHourStatus == "1")//工步
                    {
                        processRouteResult.flag = true;
                        //UpadateWorkHour(workNode.Id);
                    }
                }
                processRouteResult.code = 0;
                return processRouteResult;
                //return result;
            }
            catch (Exception ex)
            {
                processRouteResult.code = 1;
                processRouteResult.Message = ex.Message;
                processRouteResult.flag = false;
                return processRouteResult;
                //throw new UserFriendlyException(ex.Message);
            }
          
        }

        /// <summary>
        /// 计算工时
        /// </summary>
        /// <param name="workingHourStatus"></param>
        /// <param name="Id"></param>
        public void CensusWorkTime(string workingHourStatus,Guid  Id)
        {
            try
            {
                int routeType = RouteType(Id);
                if (workingHourStatus == "0") //维护工序 工时 
                {
                    if (routeType == 3) //部套-工序
                    {
                        var techId = _bopNodeRepository.Get(Id).TechniqueEntityId;
                        var process = _processesEntityRepository.GetAll().Where(d => d.TechniqueEntityId == techId).FirstOrDefault();
                        if (process != null)
                        {
                            UpadateWorkHour(process.Id);
                        }
                    }
                    if (routeType == 4)//工序-工步
                    {
                        var process = _processesEntityRepository.GetAll().Where(d => d.Id == Id).FirstOrDefault();
                        if (process != null)
                        {
                            UpadateWorkHour(process.Id);
                        }
                    }
                }
                if (workingHourStatus == "1") //维护工步 工时  底层 所以都需要维护
                {
                    if (routeType == 4)
                    {
                        var workStep = _workStepEntityRepository.GetAll().Where(d => d.ProcessesEntityId == Id).FirstOrDefault();
                        if (workStep != null)
                        {
                            UpadateWorkHour(workStep.Id);
                        }
                    }
                    if (routeType == 5)
                    {
                        var workStep = _workStepEntityRepository.GetAll().Where(d => d.Id == Id).FirstOrDefault();
                        if (workStep != null)
                        {
                            UpadateWorkHour(workStep.Id);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
           
        }

        /// <summary>
        /// 查找当前节点类型 1 任务-节点  2 节点-节点 3 节点-工序 4 工序-工步 5 工步
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        private int  RouteType(Guid ParentId)
        {
            var bopDesc =  _bopDescRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (bopDesc != null)
            {
                return 1;
            }
            var bopNode =  _bopNodeRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (bopNode != null)
            {
                if (!string.IsNullOrEmpty(bopNode.ProcessCode))
                {
                    return 3;
                }
                else
                {
                    return 2;
                }
            }
            var processEntity =  _processesEntityRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (processEntity != null)
            {
                return 4;
            }
            var workEntity =  _workStepEntityRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (workEntity != null)
            {
                return 5;
            }
            return 0;
        }
        /// <summary>
        /// 根据NodeId节点获取
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public  async Task<ProcessDesignDto>  GetProcessNodeById(Guid Id)
        {
            ProcessDesignDto processDesignDto = new ProcessDesignDto();
            processDesignDto.ParentId = Id;
            int route = RouteType(Id);
            if (route == 1)
            {
                List<ProcessNodeDto> processNodeDtos = new List<ProcessNodeDto>();
                var parentNode = await _bopDescRepository.GetAsync(Id);
                var processNodeDto = ObjectMapper.Map<ProcessNodeDto>(parentNode);
                processNodeDto.Text = parentNode.ModelName;
                processNodeDto.NodeDrawingNo = parentNode.DrawingNo;
                processNodeDtos.Add(processNodeDto);
                var bopNodes =  await  _bopNodeRepository.GetAllListAsync(d => d.BopDescId == Id&&d.ParentId==Id);
                var data = ObjectMapper.Map<List<ProcessNodeDto>>(bopNodes);
                processNodeDtos.AddRange(data);
                processDesignDto.ProcessNodeList = processNodeDtos;
                processDesignDto.ProcessLineList = ObjectMapper.Map<List<ProcessLineDto>>(_processLineRepository.GetAll().Where(d => d.PPtr == Id));

            }
            if (route == 2)
            {
                List<ProcessNodeDto> processNodeDtos = new List<ProcessNodeDto>();
                var parentNode = await _bopNodeRepository.GetAsync(Id);
                var processNodeDto = ObjectMapper.Map<ProcessNodeDto>(parentNode);
                processNodeDtos.Add(processNodeDto);
                var bopNodes = await _bopNodeRepository.GetAllListAsync(d => d.ParentId == Id);
                var data = ObjectMapper.Map<List<ProcessNodeDto>>(bopNodes);
                processNodeDtos.AddRange(data);
                processDesignDto.ProcessNodeList = processNodeDtos;
                processDesignDto.ProcessLineList = ObjectMapper.Map<List<ProcessLineDto>>(_processLineRepository.GetAll().Where(d => d.PPtr == Id));
            }
            if (route == 3)
            {
                List<ProcessNodeDto> processNodeDtos = new List<ProcessNodeDto>();
                var parentNode = await _bopNodeRepository.GetAsync(Id);
                var processNodeDto = ObjectMapper.Map<ProcessNodeDto>(parentNode);
                processNodeDtos.Add(processNodeDto);
                var techTemp = await _bopNodeRepository.FirstOrDefaultAsync(d => d.Id == Id);
                var techId = techTemp.TechniqueEntityId;
                var processList = await _processesEntityRepository.GetAllListAsync(d => d.TechniqueEntityId == techId);
                var data = ObjectMapper.Map<List<ProcessNodeDto>>(processList);
                processNodeDtos.AddRange(data);
                processDesignDto.ProcessNodeList = processNodeDtos;
                processDesignDto.ProcessLineList = ObjectMapper.Map<List<ProcessLineDto>>(_processLineRepository.GetAll().Where(d => d.PPtr == Id));
            }
            if (route == 4)
            {
                List<ProcessNodeDto> processNodeDtos = new List<ProcessNodeDto>();
                var parentNode = await _processesEntityRepository.GetAsync(Id);
                var processNodeDto = ObjectMapper.Map<ProcessNodeDto>(parentNode);
                processNodeDtos.Add(processNodeDto);
                var workList = await _workStepEntityRepository.GetAllListAsync(d => d.ProcessesEntityId == Id);
                var data = ObjectMapper.Map<List<ProcessNodeDto>>(workList);
                processNodeDtos.AddRange(data);
                processDesignDto.ProcessNodeList = processNodeDtos;
                processDesignDto.ProcessLineList = ObjectMapper.Map<List<ProcessLineDto>>(_processLineRepository.GetAll().Where(d => d.PPtr == Id));
            }
            if (route == 5)
            {
                List<ProcessNodeDto> processNodeDtos = new List<ProcessNodeDto>();
                var parentNode = await _workStepEntityRepository.GetAsync(Id);
                var processNodeDto = ObjectMapper.Map<ProcessNodeDto>(parentNode);
                processNodeDtos.Add(processNodeDto);
                processDesignDto.ProcessNodeList = processNodeDtos;
                processDesignDto.ProcessLineList = null;
            }
            return processDesignDto;
        }
        /// <summary>
        /// 引用路线
        /// </summary>
        /// <param name="Id"></param>
        public  void TransferProcessData(Guid SourceId, Guid DestinationId)
        {
            try
            {
                var processNode = _bopNodeRepository.GetAll().Where(d => d.ParentId == SourceId);
                var bopDescLoto = _bopDescRepository.Get(DestinationId).LotNo;
                Dictionary<Guid, Guid> TreeIdMap = new Dictionary<Guid, Guid>(); //统计表更前id 变更后id 然后 进行 复制变换更新
                List<TableBase> tableBases = new List<TableBase>();
                var bopDescChild = _bopNodeRepository.GetAll().Where(d => d.BopDescId == SourceId);
                foreach (var item in processNode)
                {
                    item.ParentId = DestinationId;
                    TransferTreeNode(bopDescLoto, DestinationId, item.Id, item, TreeIdMap);
                }
                TreeIdMap.Add(SourceId, DestinationId);
                //更改关系表  根据变更的id  来更新
                var lineList = _processLineRepository.GetAll().Where(d => TreeIdMap.Keys.Contains(d.PPtr));
                foreach (var item in lineList)
                {
                    if (TreeIdMap.ContainsKey(item.PPtr))
                    {
                        item.PPtr = TreeIdMap[item.PPtr];

                    }
                    if (TreeIdMap.ContainsKey(item.From))
                    {
                        item.From = TreeIdMap[item.From];

                    }
                    if (TreeIdMap.ContainsKey(item.To))
                    {
                        item.To = TreeIdMap[item.To];
                    }
                    item.Id = new Guid();
                    item.BopDescId = DestinationId;
                    _processLineRepository.Insert(item);
                }
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
           
        }
        //递归复制数据 先复制 工序 工步 规程 还有 bop节点的数据 然后 在将其路线 也 复制 更改
        private  void TransferTreeNode(string Loto,Guid bopDescId,  Guid PPtr, object parentNode, Dictionary<Guid, Guid> TreeIdMap)
        {

            int route = RouteType (PPtr);
            if (route == 2)
            {
                BopNode obj = (BopNode)parentNode;
                obj.Id = Guid.NewGuid();
                obj.BopDescId = bopDescId;
                _bopNodeRepository.Insert(obj);
                TreeIdMap.Add(PPtr, obj.Id);
                var nodes =   _bopNodeRepository.GetAll().Where(d => d.ParentId == PPtr);
                foreach (var item in nodes)
                {
                    item.ParentId = obj.Id;
                    item.BopDescId = bopDescId;
                    TransferTreeNode(Loto, bopDescId,item.Id, item, TreeIdMap);
                }
            }
            if (route == 3)
            {
                BopNode obj = (BopNode)parentNode;
                obj.Id = Guid.NewGuid();
                obj.BopDescId = bopDescId;
                obj.ExportDate = null;
                obj.BopExprot = false;
                obj.PlanExprot = false;
                obj.IsExport = 0;
                TreeIdMap.Add(PPtr, obj.Id);
                var techTemp = _bopNodeRepository.GetAll().Where(d => d.Id == PPtr).FirstOrDefault();
                var techId = techTemp.TechniqueEntityId;
                var tech = _techniqueEntityRepository.GetAll().Where(d => d.Id == techId).FirstOrDefault();
                Guid guid = Guid.NewGuid();
                if (tech != null)
                {
                    tech.Id = guid;
                    tech.Edition = Loto + "-001";
                    tech.FileStatus = FileStatus.新增;
                    tech.ProcessesEntities = null;
                    tech.CreationTime = DateTime.Now;
                    tech.Property = TechAttribute.Bop引入;
                    var proc = _processesEntityRepository.GetAll().Where(d => d.TechniqueEntityId == techId).ToList();
                    foreach (var item in proc)
                    {
                        item.TechniqueEntityId = guid;
                        TransferTreeNode(Loto, bopDescId,item.Id, item, TreeIdMap);
                    }
                    obj.TechniqueEntityId = guid;
                    _bopNodeRepository.Insert(obj);
                    _techniqueEntityRepository.Insert(tech);
                    var newProcessesList = _processesEntityRepository.GetAllIncluding(p => p.WorkStepEntities).Where(p => p.TechniqueEntityId == techId);
                    foreach (var item in newProcessesList)
                    {
                        item.TechniqueEntityId = tech.Id;
                        var  proGuid = Guid.NewGuid();
                        TreeIdMap.Add(item.Id, proGuid);
                        item.Id = proGuid;
                        _processesEntityRepository.Insert(item);
                        foreach (var temp in item.WorkStepEntities)
                        {
                            var workGuid = Guid.NewGuid();
                            TreeIdMap.Add(temp.Id, workGuid);
                            var loadList = _loadPieceRepository.GetAll().Where(d => d.WorkStepEntityId == temp.Id);
                            var makeList = _makeResourcesEntityRepository.GetAll().Where(d => d.WorkStepEntityId == temp.Id);
                            var videoList = _videoEntityRepository.GetAll().Where(d => d.WorkStepEntityId == temp.Id);
                            foreach (var load in loadList)
                            {
                                load.Id = Guid.NewGuid();
                                load.WorkStepEntityId = workGuid;
                                _loadPieceRepository.Insert(load);
                            }
                            foreach (var make in makeList)
                            {
                                make.Id = Guid.NewGuid();
                                make.WorkStepEntityId = workGuid;
                                _makeResourcesEntityRepository.Insert(make);
                            }
                            foreach (var video in videoList)
                            {
                                video.Id = Guid.NewGuid();
                                video.WorkStepEntityId = workGuid;
                                _videoEntityRepository.Insert(video);
                            }

                            temp.Id = workGuid;
                            temp.ProcessesEntityId = item.Id;
                            temp.TechniqueEntityId = tech.Id;
                            _workStepEntityRepository.Insert(temp);
                        }
                    }
                    var workList = _workStepEntityRepository.GetAll().Where(d => d.TechniqueEntityId == techId).Select(d => d.Id);
                    var tableData = _tableBaseEntity.GetAllIncluding(a => a.RecordRequirements, b => b.InspectionSignature, c => c.MeasuredResult, d => d.Environment, e => e.MultiMedia).Where(d => workList.Contains(d.WorkStepEntityId));
                    foreach (var item in tableData)
                    {
                        ConvertFormBase cFormbase = new ConvertFormBase(Guid.NewGuid(), item.FormName, item.SerialNum, TreeIdMap[item.WorkStepEntityId], TreeIdMap[item.ProcessesEntityId], item.Sort, item.Deptment,
                        item.ParentProductNum, item.ParentProductNum_DisplayName,
                        item.ParentProductNum_Enable, item.ParentProductNum_Show, item.ParentProductNum_Property, item.ParentProductName, item.ParentProductName_DisplayName, item.ParentProductName_Enable, item.ParentProductName_Show,
                        item.ParentProductName_Property, item.FisrtDrawingNum, item.FisrtDrawingNum_DisplayName, item.FisrtDrawingNum_Enable, item.FisrtDrawingNum_Show, item.FisrtDrawingNum_Property,
                        item.FirstDrawingName, item.FirstDrawingName_DisplayName, item.FirstDrawingName_Enable, item.FirstDrawingName_Show, item.FirstDrawingName_Property,
                        item.SecondDrawingNum, item.SecondDrawingNum_DisplayName, item.SecondDrawingNum_Enable, item.SecondDrawingNum_Show, item.SecondDrawingNum_Property,
                        item.SecondDrawingName, item.SecondDrawingName_DisplayName, item.SecondDrawingName_Enable, item.SecondDrawingName_Show, item.SecondDrawingName_Property,
                        item.ProductNum, item.ProductNum_DisplayName, item.ProductNum_Enable, item.ProductNum_Show, item.ProductNum_Property,
                        item.Model, item.Model_DisplayName, item.Model_Enable, item.Model_Show, item.Model_Property, item.RecordElement, item.RecordElement_DisplayName, item.RecordElement_Enable,
                        item.RecordElement_Show, item.RecordElement_Property, item.RecordItem, item.RecordItem_DisplayName, item.RecordItem_Enable, item.RecordItem_Show, item.RecordItem_Property,
                        item.ToolUsed, item.ToolUsed_DisplayName, item.ToolUsed_Enable, item.ToolUsed_Show, item.ToolUsed_Property, item.AbnormalRecord, item.AbnormalRecord_DisplayName,
                        item.AbnormalRecord_Enable, item.AbnormalRecord_Show, item.AbnormalRecord_Property, item.Certificate, item.Certificate_DisplayName, item.Certificate_Enable,
                        item.Certificate_Show, item.Certificate_Property, item.SecondToolUsed, item.SecondToolUsed_DisplayName, item.SecondToolUsed_Enable, item.SecondToolUsed_Show,
                        item.SecondToolUsed_Property, item.ThirdToolUsed, item.ThirdToolUsed_DisplayName, item.ThirdToolUsed_Enable, item.ThirdToolUsed_Show, item.ThirdToolUsed_Property,
                        item.ParamCode, item.ParamCode_DisplayName, item.ParamCode_Enable, item.ParamCode_Show, item.ParamCode_Property

                        );
                        if (item.InspectionSignature != null)
                        {
                            cFormbase.InspectionSignature = cFormbase.SetInspectionSignature(item.InspectionSignature);
                        }
                        if (item.RecordRequirements != null)
                        {
                            cFormbase.RecordRequirements = cFormbase.SetRecordRequirements(item.RecordRequirements);
                        }
                        if (item.MultiMedia != null)
                        {
                            cFormbase.MultiMedia = cFormbase.SetMultiMedia(item.MultiMedia);
                        }
                        if (item.MeasuredResult != null)
                        {
                            cFormbase.MeasuredResult = cFormbase.SetMeasuredResult(item.MeasuredResult);
                        }
                        if (item.Environment != null)
                        {
                            cFormbase.Environment = cFormbase.SetEnvironment(item.Environment);
                        }
                        _convertFormBaseEntity.Insert(cFormbase);
                    }
                }
                else
                {
                    obj.TechniqueEntityId = null;
                    _bopNodeRepository.Insert(obj);
                }
            }
          
        }

        /// <summary>
        /// 根据NodeId节点获取工序与工步树
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public TreeNodeDto GetWorkTree(Guid Id)
        {
            var bopNode = _bopNodeRepository.FirstOrDefault(x => x.Id == Id);
            string processCode = bopNode.ProcessCode;
            if (string.IsNullOrEmpty(processCode)) return new TreeNodeDto();
            //根据工艺规程编码获取工艺文件表Id,已关联文件
            var tech = _techniqueEntityRepository.FirstOrDefault(x => x.Id == bopNode.TechniqueEntityId);
            Guid techId = tech.Id;
            //获取工序和工步的信息，并做相应的排序
            var processesList = _processesEntityRepository.GetAllIncluding(p => p.WorkStepEntities).Where(p => p.TechniqueEntityId == techId).OrderBy(n => n.ProcessesSequence);
            TreeNodeDto treeNodeDto = new TreeNodeDto();
            //循环遍历，往Node里面赋值
            foreach (var item in processesList)
            {
                TreeNodeDto tree = new TreeNodeDto();
                tree.Id = item.Id;
                tree.ParentId = Id;
                tree.NodeName = item.ProcessesName;
                item.WorkStepEntities = item.WorkStepEntities.OrderBy(r => r.WorkStepNumber).ToList();
                tree.NodeLevel = 8;
                //查询工步
                foreach (var witem in item.WorkStepEntities)
                {
                    TreeNodeDto wtree = new TreeNodeDto();
                    wtree.Id = witem.Id;
                    wtree.ParentId = item.Id;
                    wtree.NodeName = witem.WorkStepName;
                    wtree.NodeLevel = 9;
                    tree.TreeList.Add(wtree);
                }
                treeNodeDto.TreeList.Add(tree);
            }
            return treeNodeDto;
        }

        /// <summary>
        /// 查询树结构
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public TreeNodeDto GetProcessTree(Guid Id)
        {
            TreeNodeDto treeNodeDto = new TreeNodeDto();
            SelectChildNode(Id, treeNodeDto);
            return treeNodeDto;
        }
        /// <summary>
        /// 递归展示树结构
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="treeNodeDto"></param>
        private void SelectChildNode(Guid Id, TreeNodeDto treeNodeDto)
        {
            TreeNodeDto treeNode = new TreeNodeDto();
            var node = _bopNodeRepository.Get(Id);
            treeNode.Id = node.Id;
            treeNode.NodeName = node.NodeName;
            treeNode.ParentId = node.ParentId;
            treeNode.NodeLevel = node.NodeLevel;
            treeNode.IsLeaf = node.IsLeaf;
            treeNode.Sort = node.Sort;
            var childNodes = _bopNodeRepository.GetAll().Where(d => d.ParentId == Id);
            foreach (var item in childNodes)
            {
                TreeNodeDto childNode = new TreeNodeDto();
                childNode.Id = item.Id;
                childNode.NodeName = item.NodeName;
                childNode.ParentId = item.ParentId;
                childNode.NodeLevel = item.NodeLevel;
                childNode.IsLeaf = item.IsLeaf;
                childNode.Sort = item.Sort;
                SelectChildNode(item.Id, childNode);
                treeNode.TreeList.Add(childNode);
            }
            treeNodeDto.TreeList.Add(treeNode);
        }
        private decimal CalculationWorkHour(ProcessDesignDto processDesignDto)
        {
            List<decimal> compute = new List<decimal>();
            if (processDesignDto.ProcessLineList.Count > 0)
            {
                foreach (var item in processDesignDto.ProcessLineList)
                {
                    decimal itemCompute;
                    var pt = processDesignDto.ProcessNodeList.Where(d => d.Key == item.From).FirstOrDefault();
                    if (pt != null)
                    {
                        itemCompute = pt.WorkingHour + ComputeWorkHour(processDesignDto.ProcessLineList, processDesignDto.ProcessNodeList, item.To);
                    }
                    else
                    {
                        itemCompute =0 + ComputeWorkHour(processDesignDto.ProcessLineList, processDesignDto.ProcessNodeList, item.To);
                    }

                     
                    compute.Add(itemCompute);
                }
                return compute.Max();
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// 递归计算最长工时
        /// </summary>
        /// <param name="processLines"></param>
        /// <param name="processNodes"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        private decimal ComputeWorkHour(List<ProcessLineDto> processLines, List<ProcessNodeDto> processNodes, Guid to)
        {
            decimal conut = 0;
            var child = processLines.FirstOrDefault(d => d.From == to);
            string s = "";
            if (child != null)
            {

                var pt = processNodes.FirstOrDefault(d => d.Key == child.From);
                if (pt != null)
                {
                    conut = conut + pt.WorkingHour + ComputeWorkHour(processLines, processNodes, child.To);
                }
                else
                {
                    conut = conut +0 + ComputeWorkHour(processLines, processNodes, child.To);
                } 
            }
            return conut;
        }
        /// <summary>
        /// 递归修改父节点工时
        /// </summary>
        private  void UpadateWorkHour(Guid Id)
        {
            ProcessDesignDto processDesign = new ProcessDesignDto();
            int routeType =  RouteType(Id);
            if (routeType == 5)
            {
                var parentTemp =  _workStepEntityRepository.Get(Id);
                var parentNode = _processesEntityRepository.Get(parentTemp.ProcessesEntityId);
                processDesign.ParentId = parentTemp.ProcessesEntityId;
                var workTemp = _workStepEntityRepository.GetAll().Where(d => d.ProcessesEntityId == parentNode.Id);
                var proTemp = _processLineRepository.GetAll().Where(d => d.PPtr == parentNode.Id);
                processDesign.ProcessNodeList = ObjectMapper.Map<List<ProcessNodeDto>>(workTemp);
                processDesign.ProcessLineList = ObjectMapper.Map<List<ProcessLineDto>>(proTemp);
                parentNode.ProcessesWorking = CalculationWorkHour(processDesign);
                _processesEntityRepository.Update(parentNode);
                var plan= _productionSchedulerRepository.GetAll().Where(d => d.NodeId == parentNode.Id).FirstOrDefault();
                if (plan != null)
                {
                    plan.WorkingHour = parentNode.ProcessesWorking;
                    _productionSchedulerRepository.Update(plan);
                }
                UpadateWorkHour(parentTemp.ProcessesEntityId);
            }
            if (routeType == 4)
            {
                var parentTemp =  _processesEntityRepository.Get(Id);
                var bopNode = _bopNodeRepository.GetAll().Where(d => d.TechniqueEntityId == parentTemp.TechniqueEntityId).FirstOrDefault();
                processDesign.ParentId = bopNode.Id;
                processDesign.ProcessNodeList = ObjectMapper.Map<List<ProcessNodeDto>>(_processesEntityRepository.GetAll().Where(d => d.TechniqueEntityId == parentTemp.TechniqueEntityId));
                processDesign.ProcessLineList = ObjectMapper.Map<List<ProcessLineDto>>(_processLineRepository.GetAll().Where(d => d.PPtr == bopNode.Id));
                bopNode.WorkingHour = CalculationWorkHour(processDesign);
                _bopNodeRepository.Update(bopNode);
                var plan = _productionSchedulerRepository.GetAll().Where(d => d.NodeId == bopNode.Id).FirstOrDefault();
                if (plan != null)
                {
                    plan.WorkingHour = bopNode.WorkingHour;
                    _productionSchedulerRepository.Update(plan);
                }
                UpadateWorkHour(bopNode.Id);
            }
            if (routeType == 3 || routeType == 2)
            {
                var parentTemp = _bopNodeRepository.Get(Id);
                var parentNode = _bopNodeRepository.GetAll().Where(d => d.Id == parentTemp.ParentId).FirstOrDefault();
                if (parentNode != null)
                {
                    processDesign.ParentId = parentNode.Id;
                    var workTemp = _bopNodeRepository.GetAll().Where(d => d.ParentId == parentNode.Id);
                    var proTemp =  _processLineRepository.GetAll().Where(d => d.PPtr == parentNode.Id);
                    processDesign.ProcessNodeList = ObjectMapper.Map<List<ProcessNodeDto>>(workTemp);
                    processDesign.ProcessLineList = ObjectMapper.Map<List<ProcessLineDto>>(proTemp);
                    parentNode.WorkingHour = CalculationWorkHour(processDesign);
                     _bopNodeRepository.Update(parentNode);
                    var plan = _productionSchedulerRepository.GetAll().Where(d => d.NodeId == parentNode.Id).FirstOrDefault();
                    if (plan != null)
                    {
                        plan.WorkingHour = parentNode.WorkingHour;
                        _productionSchedulerRepository.Update(plan);
                    }
                    UpadateWorkHour(parentNode.Id);
                }
                else
                {
                    var BopDescNode = _bopDescRepository.GetAll().Where(d => d.Id == parentTemp.BopDescId).FirstOrDefault();
                    processDesign.ParentId = BopDescNode.Id;
                    var workTemp =  _bopNodeRepository.GetAll().Where(d => d.BopDescId == BopDescNode.Id);
                    var proTemp =  _processLineRepository.GetAll().Where(d => d.PPtr == BopDescNode.Id);
                    processDesign.ProcessNodeList = ObjectMapper.Map<List<ProcessNodeDto>>(workTemp);
                    processDesign.ProcessLineList = ObjectMapper.Map<List<ProcessLineDto>>(proTemp);
                    BopDescNode.WorkingHour = CalculationWorkHour(processDesign);
                    _bopDescRepository.Update(BopDescNode);
                    return;
                }

            }
            if (routeType == 1)
            {
                return;
            }
        }
    }
}
